<template>
  <div ref="chartDom" :style="{ width: width, height: height }"></div>
</template>
<script setup>
import {onMounted, onBeforeUnmount, watch, nextTick, useTemplateRef} from "vue";
import {useWindowSize} from "@vant/use";
import * as echarts from 'echarts/core';
import {GridComponent, LegendComponent, TooltipComponent} from 'echarts/components';
import {BarChart} from 'echarts/charts';
import {CanvasRenderer} from 'echarts/renderers';
import {usePublicStore} from "@/stores/publicInfo.js";

const publicStore = usePublicStore()
echarts.use([GridComponent, LegendComponent, TooltipComponent, BarChart, CanvasRenderer]);


// 定义 Props
const props = defineProps({
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "300px",
  },
  chartData: {
    type: Object,
    default: () => {
    }
  },
});


// 绑定 DOM 元素
const chartDom = useTemplateRef('chartDom');
let chartInstance = null; // ECharts 实例

// Custom colors
const colors = {
  workday: '#f4b183',
  weekend: '#9dc3e6'
};
const {xAxisData, workdayOvertime, weekendOvertime} = props.chartData
// 初始化图表
const initChart = () => {
  if (!chartDom.value) {
    console.error("DOM 元素未找到！");
    return;
  }
  const options =
    {
      legend: {
        data: ['工作日加班时长', '休息日加班时长'],
        bottom: 0,
        itemWidth: 20,
        itemHeight: 10
      },
      grid: {
        left: '2%',
        right: '2%',
        bottom: '10%',
        top: '10px',
        containLabel: true
      },
      tooltip: {
        show: !publicStore.isMobile,
        trigger: 'axis',
        axisPointer: {type: 'shadow'},
        formatter: (params) => {
          const name = params[0].name;
          const workHours = params[0].value;
          const weekendHours = params[1].value;
          return `
      ${name}<br/>
      <span style="color:${colors.workday}">●</span> 工作日: ${workHours.toFixed(2)}小时<br/>
      <span style="color:${colors.weekend}">●</span> 休息日: ${weekendHours.toFixed(2)}小时<br/>
      <strong>总时长: ${(workHours + weekendHours).toFixed(2)}小时</strong>
    `;
        }
      },
      xAxis: {
        type: 'category',
        data: xAxisData,
        axisLabel: {
          interval: 0,
          rotate: xAxisData.some(name => name.length > 3) ? 30 : 0
        }
      },
      yAxis: {
        show: false, // Hide Y axis as requested
        type: 'value'
      },
      series: [
        {
          name: '工作日加班时长',
          type: 'bar',
          stack: 'total', // Stack the bars
          barWidth: '60%',
          itemStyle: {
            color: colors.workday,
            // borderRadius: [4, 4, 0, 0]
          },
          data: workdayOvertime.map(hours => hours > 0 ? parseFloat(hours.toFixed(2)) : 0),
          label: {
            show: true,
            position: 'inside',
            formatter: params => params.value > 0 ? params.value.toFixed(2) : '',
            color: '#fff'
          }
        },
        {
          name: '休息日加班时长',
          type: 'bar',
          stack: 'total', // Stack on top of workday
          barWidth: '60%',
          itemStyle: {
            color: colors.weekend,
            // borderRadius: [0, 0, 4, 4]
          },
          data: weekendOvertime.map(hours => hours > 0 ? parseFloat(hours.toFixed(2)) : 0),
          label: {
            show: true,
            position: 'inside',
            formatter: params => params.value > 0 ? params.value.toFixed(2) : '',
            color: '#fff'
          }
        }
      ]
    }
  // 确保 DOM 已渲染且尺寸有效
  nextTick(() => {
    chartInstance = echarts.init(chartDom.value);
    chartInstance.setOption(options);
  });
};

// 监听窗口尺寸变化
const {width: windowWidth, height: windowHeight} = useWindowSize();
watch([windowWidth, windowHeight], () => {
  if (chartInstance) {
    nextTick(() => {
      chartInstance.resize(); // 窗口变化时重新调整图表
    });
  }
});

// 监听 option 变化
watch(
  () => props.chartData,
  (newVal) => {
    initChart()
  },
  {deep: true}
);

// 生命周期
onMounted(() => {
  initChart(); // 确保在 DOM 挂载后初始化
});

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose(); // 销毁实例
  }
});

</script>
